<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    okText="保存"
    width="70%"
    :okAuth="'asd:tl:asdTmTl:edit'"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    
    <BasicForm @register="registerForm">
      <template #PosDataChildList>
        <BasicTable
          @register="registerPosDataChildTable"
          @row-click="handleTestDataChildRowClick"
          @selection-change="selectFnc"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsPosForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { asdTmLlHPosForm } from '/@/api/asd/ll/asdTmLl';
  import { bacthSave } from '/@/api/asd/ll/asdTmLlPos';
  import { BasicTable, useTable } from '/@/components/Table';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.m8OperCheck');
  const { showMessage } = useMessage();
  const record = ref<any>({
    picSumQty: '',
    checkSumQty: '',
    checkList: [],
  });
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: '货位存量选择',
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t(''),
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: t('物料编码'),
      field: 'basInv.cinvcode',
      component: 'Input',
      dynamicDisabled: true,
      required: false,
    },
    {
      label: t('物料名称'),
      field: 'basInv.cinvname',
      component: 'Input',
      dynamicDisabled: true,
      required: false,
    },
    {
      label: t('物料代码'),
      field: 'basInv.cinvaddcode',
      component: 'Input',
      dynamicDisabled: true,
      required: false,
    },
    {
      label: t('需求数'),
      field: 'iqty',
      component: 'Input',
      dynamicDisabled: true,
      required: false,
    },
    {
      label: t('库存量'),
      field: 'xqty',
      component: 'Input',
      dynamicDisabled: true,
      required: false,
    },
    {
      label: '',
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'PosDataChildList',
    },
  ];

  const [registerPosDataChildTable, posDataChildTable] = useTable({
    rowKey: 'id',
    pagination: false,
    bordered: true,
    canResize: true,
    resizeHeightOffset: 80,
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await asdTmLlHPosForm(data);
    record.value = res;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setPosDataChildTableData(res);
    setDrawerProps({ loading: false });
  });

  async function setPosDataChildTableData(_res: Recordable) {
    posDataChildTable.setColumns([
      {
        title: t('仓库'),
        dataIndex: 'cwhcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('区域'),
        dataIndex: 'areacode',
        width: 130,
        align: 'left',
      },
      {
        title: t('货位编码'),
        dataIndex: 'cposcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('货位名称'),
        dataIndex: 'cposname',
        width: 130,
        align: 'left',
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 130,
        align: 'left',
      },
      {
        title: t('现存量'),
        dataIndex: 'iquantity',
        width: 60,
        align: 'left',
      },
      {
        title: t('下架数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
          rules: [
            {
              pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
              message: t('请输入一个数值'),
            },
          ],
        },
        editRule: true,
      },
    ]);
    posDataChildTable.setTableData(record.value.list || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function selectFnc(val) {
    var qty = 0;
    val.rows.forEach((element) => {

      qty += element.xjQty;
    });
  }

  async function getPosDataChildList() {
    let posDataChildListValid = true;
    let posDataChildList: Recordable[] = [];
    for (const record of posDataChildTable.getSelectRows()) {
      // 验证控件内容，并取消行的编辑状态（如果验证失败返回false）
      if (!(await record.onEdit?.(false, true))) {
        posDataChildListValid = false;
      }
      posDataChildList.push({
        ...record,
      });
    }

    if (!posDataChildListValid) {
      throw { errorFields: [{ name: ['posDataChildList'] }] };
    }
    return posDataChildList;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      let flag = true;

      //获取数据
      let arr = await getPosDataChildList();
      var qty = 0;
      if (arr.length < 1) {
        showMessage(t('未选择货位，不能保存!'));
        return;
      }
      for (const ar of arr) {
        if (ar.iqty == undefined || ar.iqty == '' || +ar.iqty <= 0) {
          showMessage(t('数量不能为0!'));
          return;
        }
        // if (+ar.iqty > ar.iquantity) {
        //   showMessage(t('下架数量不能大于现存量!'));
        //   return;
        // }
        qty += ar.iqty;
      }

      // if (data.iqty - qty > 0) {
      //   showMessage(t('选择下架数小于需求数，不能保存!'));
      //   return;
      // }

      const params: any = {
        selIds: JSON.stringify(arr),
        did: data.id,
      };

      if (flag) {
        const res = await bacthSave(params);
        showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
